package com.founder.barcode.bussiness.code;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;

import com.founder.barcode.common.util.MD5Util;
import com.founder.barcode.taobao.util.TaobaoUtil;

public class BuildRequest {
    
    protected String transferMap(Map<String, String> requestMap) {
        StringBuffer buf = new StringBuffer();
        for(Entry<String, String> entry : requestMap.entrySet()) {
            buf.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        if(buf.length() > 0) {
            buf.deleteCharAt(buf.length()-1);
        }
        return buf.toString();
    }
    
    /**
     * 测试请求参数
     * @param map
     * @return
     */
    public String getRequestSign(Map<String, String> map){
        String secret = TaobaoUtil.appSecurity();// 通知验证密钥
        String sign = "";
        Map<String, String> signMap = new TreeMap<String, String>();
        StringBuilder paramsString = new StringBuilder();
        for(Entry<String, String> entry : map.entrySet()) {
            if("sign".equals(entry.getKey()) || StringUtils.isEmpty(entry.getValue()))
                continue;
            signMap.put(entry.getKey(), entry.getValue());
        }
        paramsString.append(secret);
        for(Entry<String, String> entry : signMap.entrySet()) {
            paramsString.append(entry.getKey()).append(entry.getValue());
        }
        try {
            sign = MD5Util.encodeByMD5(new String(paramsString.toString().getBytes("utf-8"))).toUpperCase();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return sign;
    }
    
    public String taobaoCodeMake(String order_id,String mobile,
            String token,String send_type,String sms_template) {
        Map<String, String> requestMap = new HashMap<String, String>();
        requestMap.put("order_id", order_id);
        requestMap.put("send_type", send_type);
        requestMap.put("mobile", mobile);
        requestMap.put("token", token);
        requestMap.put("sms_template", sms_template);
        requestMap.put("method", "send");
        String sign = this.getRequestSign(requestMap);
        requestMap.put("sign", sign);
        return this.transferMap(requestMap);
    }
}
